from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, HttpResponseRedirect, redirect, reverse
from django import forms
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from common.get_log import GetLog
from projects.models import Projects

logging = GetLog.get_logger()
# Create your views here.
from users.models import UserProfile


class UserForm(forms.Form):
    username = forms.CharField(max_length=50, label='用户名', required=True,
                               widget=forms.TextInput(
                                   attrs={'class': 'form-control', "placeholder": "Email/Phone/Username"}))
    password = forms.CharField(max_length=16, min_length=8, label='密码', required=True,
                               widget=forms.TextInput(
                                   attrs={'class': 'form-control', "placeholder": "Password", 'type': "password"}))


class CustomBackends(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username) | Q(phone=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


@login_required(login_url='/users/login')
def index(request):
    projects_list = Projects.objects.all().order_by('-create_time')
    is_project = request.GET.get('is_project', None)
    if is_project is None:
        is_project = 45
    res = render(request, 'index.html', {"is_project": int(is_project), "projects_list": projects_list})
    res.set_cookie("Project", int(is_project))
    return res


def user_login(request):
    if request.method == "POST":
        login_form = UserForm(request.POST)
        logging.info("用户发送登录请求：" + str(request.POST))
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            logging.info("用户输入数据：{}，密码：{}".format(username, password))
            logging.info("用户数据是否存在" + str(user))
            if user:
                login(request, user)
                logging.info("用户登陆成功，跳转首页")
                return HttpResponseRedirect(reverse('index'))
            logging.info("用户登录失败，账户名或密码错误")
            return render(request, 'page-login.html', {'login_form': login_form, 'error_msg': '账户名或密码错误'})
    login_form = UserForm()
    logging.info("用户进入登录页面")
    return render(request, 'page-login.html', {'login_form': login_form})


def user_logout(request):
    logging.info("用户退出登录" + str(request.user))
    logout(request=request)
    return HttpResponseRedirect(reverse('index'))
